<template>
  <div class="employee-container">
	  <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	          <el-col :span="24" class="text-center">
	              <div class="title-wrapper">
	              <i class="el-icon-search el-icon--large"></i>
	              <h1 class="main-title">员工信息管理系统</h1>
	              <p class="sub-title">每一份用心付出，都值得被看见；每一位并肩同行的你，都是团队最坚实的力量</p>
	              </div>
	          </el-col>
	      </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="员工详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="员工信息" direction="vertical" :column="4" :model="messageForm" border>
        <el-descriptions-item label="员工ID" :span="2">{{ messageForm.employeeid }}</el-descriptions-item>
        <el-descriptions-item label="姓名" :span="2">{{ messageForm.name }}</el-descriptions-item>
        <el-descriptions-item label="职位" :span="2">{{ messageForm.position }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">{{ messageForm.status }}</el-descriptions-item>
        <el-descriptions-item label="账号" :span="2">{{ messageForm.account }}</el-descriptions-item>
        <el-descriptions-item label="手机号码" :span="2">{{ messageForm.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="入职日期" :span="2">{{ formatDate(messageForm.hireDate) }}</el-descriptions-item>
        <el-descriptions-item label="最后登录" :span="2">{{ formatDate(messageForm.lastLogin) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑员工"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="account">
              <el-input v-model="ruleForm.account"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="ruleForm.phoneNumber" type="tel"></el-input>
            </el-form-item>
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker v-model="ruleForm.hireDate" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
            <el-option label="休假" value="休假"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="ruleForm.position" placeholder="请选择职位">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="保安" value="保安"></el-option>
            <el-option label="保洁" value="保洁"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定修改</el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="新增员工"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="account">
              <el-input v-model="addForm.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="addForm.password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber" type="tel"></el-input>
            </el-form-item>
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker v-model="addForm.hireDate" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
            <el-option label="休假" value="休假"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="addForm.position" placeholder="请选择职位">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="保安" value="保安"></el-option>
            <el-option label="保洁" value="保洁"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">确定添加</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示表界面 -->
    <el-row style="width: 100%;">
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px;">
        <el-col :span="6">
          <el-input 
            placeholder="输入姓名查询" 
            v-model="Condition.searchQuery" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="Condition.selectedCategory" 
            placeholder="选择职位" 
            style="width: 100%;"
          >
            <el-option label="全部职位" value=""></el-option>
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="保安" value="保安"></el-option>
            <el-option label="保洁" value="保洁"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="Condition.selectedCategory2" 
            placeholder="选择状态" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
            <el-option label="休假" value="休假"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            icon="el-icon-plus" 
            @click="openDetails2" 
            style="width: 100%;"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
      
      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="employeeid" label="员工ID" width="160" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="160" align="center"></el-table-column>
        <el-table-column prop="position" label="职位" width="160" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="140" align="center"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号码" width="250" align="center"></el-table-column>
        <el-table-column prop="hireDate" label="入职日期" width="300" align="center" :formatter="formatDate"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetails(scope.row)">查看</el-button>
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openDetails1(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

// 对话框控制变量
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)

// 搜索条件
const Condition = reactive({
  searchQuery: '',
  selectedCategory: '',
  selectedCategory2: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const tableData = ref([])

// 表单引用
const ruleFormRef = ref(null)
const addFormRef = ref(null)

// 详情表单数据
const messageForm = reactive({
  employeeid: '',
  name: '',
  position: '',
  status: '',
  account: '',
  phoneNumber: '',
  hireDate: '',
  lastLogin: ''
})

// 编辑表单数据
const ruleForm = reactive({
  employeeid: '',
  name: '',
  position: '',
  status: '',
  account: '',
  phoneNumber: '',
  hireDate: null
})

// 新增表单数据
const addForm = reactive({
  name: '',
  position: '',
  status: '',
  account: '',
  password: '',
  phoneNumber: '',
  hireDate: null
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ]
})

// 日期格式化
// 修改日期格式化函数，使其兼容两种调用方式
// 日期格式化：兼容「表格formatter」和「详情对话框」两种调用场景
const formatDate = (param1, param2, param3) => {
  let value = '';
  // 场景1：表格formatter调用（传递3个参数：row, column, cellValue）
  if (param3 !== undefined) { 
    value = param3; // 直接取第三个参数（单元格原始值）
  } 
  // 场景2：详情对话框调用（仅传递1个参数：messageForm.hireDate）
  else { 
    value = param1; // 取第一个参数（直接传入的日期值）
  }

  // 过滤无效值
  if (!value || value === 'null' || value === 'undefined') return '';

  // 统一转换为Date对象（兼容字符串、时间戳）
  let date;
  if (typeof value === 'number') {
    date = new Date(value); // 处理时间戳（如1725686400000）
  } else {
    date = new Date(value); // 处理字符串（如'2024-09-07'）
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) return '无效日期';

  // 格式化为「YYYY-MM-DD」
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 打开详情对话框
function openDetails(row) {
  dialogVisible.value = true
  Object.assign(messageForm, row)
}

// 打开编辑对话框
function openDetails1(row) {
  dialogVisible1.value = true
  // 深拷贝行数据到表单
  Object.keys(ruleForm).forEach(key => {
    if (key === 'hireDate' && row[key]) {
      ruleForm[key] = new Date(row[key])
    } else {
      ruleForm[key] = row[key] ?? ''
    }
  })
}

// 打开新增对话框
function openDetails2() {
  dialogVisible2.value = true
  // 重置表单
  Object.keys(addForm).forEach(key => {
    addForm[key] = key === 'hireDate' ? null : ''
  })
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 分页大小改变
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页改变
function handleCurrentChange(val) {
  currentPage.value = val
}

// 提交编辑表单
function submitForm() {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return

    // 格式化日期
    let formData = { ...ruleForm }
    if (formData.hireDate) {
      formData.hireDate = formatDate(null, null, formData.hireDate)
    }

    const loading = ElLoading.service({ text: '修改中...' })
    post('/sc/employee/update', formData, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('修改成功！')
        dialogVisible1.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '修改失败')
      }
    })
  })
}

// 处理新增
function handleAdd() {
  addFormRef.value.validate((valid) => {
    if (!valid) return

    // 格式化日期
    let formData = { ...addForm }
    if (formData.hireDate) {
      formData.hireDate = formatDate(null, null, formData.hireDate)
    }

    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/employee/add', formData, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('添加成功！')
        dialogVisible2.value = false
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 处理删除
function handleDelete(row) {
  ElMessageBox.confirm(`确定删除员工 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/employee/deleteById', { employeid: row.employeeid }, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('删除成功！')
        fetchTableData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 搜索员工
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  post('/sc/employee/getByCondition', {
    account: null,
    name: Condition.searchQuery,
    position: Condition.selectedCategory,
    status: Condition.selectedCategory2
  }, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success(`找到 ${res.data.length} 条记录`)
    } else {
      tableData.value = []
      ElMessage.warning('未找到匹配记录')
    }
  })
}

// 获取所有员工数据
function fetchTableData() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/employee/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  })
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.employee-container {
  width: 100%; /* 改为100%，确保最外层占满父容器 */
  box-sizing: border-box; /* 可选：防止padding影响宽度计算 */
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}
</style>